# inc/logger.py
from datetime import datetime, timedelta
import logging
from functools import wraps

from flask import request, current_app
from flask_login import current_user

from .models import OperationLog, BackupLog, db



def log_operation(action, resource, details_func=None):
    """
    操作日志装饰器
    :param action: 操作名称
    :param resource: 操作资源
    :param details_func: 生成详细信息的函数，接收视图函数返回值
    """

    def decorator(f):
        @wraps(f)
        def decorated_function(*args, **kwargs):
            # 执行视图函数
            result = f(*args, **kwargs)

            # 设置日志级别为WARNING，减少INFO日志输出
            logging.getLogger().setLevel(logging.WARNING)

            # 记录操作日志
            try:
                # 尝试加载系统配置
                try:
                    from inc.config_manager import load_system_config
                    load_system_config()
                except Exception as load_error:
                    current_app.logger.warning(f"加载系统配置失败: {str(load_error)}")
                    # 即使加载失败也继续记录日志，但使用默认配置
                    pass

                # 检查是否启用了操作日志（默认启用）
                should_log = True
                if hasattr(current_app,
                           'system_config') and current_app.system_config.operation_log_enabled is not None:
                    should_log = current_app.system_config.operation_log_enabled
                else:
                    # 如果无法获取配置，默认启用日志
                    should_log = True

                if should_log:
                    details = details_func(result) if details_func else f"执行了 {action} 操作"

                    OperationLog.create(
                        admin_id=current_user.id if current_user.is_authenticated else None,
                        action=action,
                        resource=resource,
                        details=details,
                        success=True,  # 可根据实际情况调整
                        ip_address=request.remote_addr
                    )
            except Exception as e:
                current_app.logger.error(f"记录操作日志失败: {str(e)}")

            return result

        return decorated_function

    return decorator


def log_backup(backup_type, filename, file_size, operator_id, status="success"):
    """记录备份日志"""
    try:
        # 直接创建备份日志对象并保存到数据库
        backup_log = BackupLog(
            backup_type=backup_type,
            filename=filename,
            file_size=file_size,
            operator_id=operator_id,
            status=status,
            backup_time=datetime.now()
        )

        db.session.add(backup_log)
        db.session.commit()
        return True

    except Exception as e:
        # 如果记录日志失败，尝试使用 current_app 记录错误
        try:
            current_app.logger.error(f"记录备份日志失败: {str(e)}", exc_info=True)
        except:
            # 如果 current_app 也不可用，使用基本的日志记录
            logging.error(f"记录备份日志失败: {str(e)}", exc_info=True)
        return False